﻿/********************************************************************************
    Copyright (C) Binod Nepal, Planet Earth Solutions Pvt. Ltd., Kathmandu.
	Released under the terms of the GNU General Public License, GPL, 
	as published by the Free Software Foundation, either version 3 
	of the License, or (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
    See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
***********************************************************************************/

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Pes.Utility;
using System.Text;
using System.Web.Services;

namespace MixNP.Web.Classifieds
{
    public partial class ItemView : MixNP.BusinessLayer.BaseClass
    {
        string rootCategoryAlias;
        int rootCategoryId;
        string categoryAlias;
        int categoryId;
        double itemId;
        string alias;
        string itemTitle;
        string details;
        string userSalt;

        private void CommentAdded()
        {
            if (MixNP.BusinessLayer.Email.SendCommentAlert(this.Page, itemId))
            {
                MixNP.BusinessLayer.Email.ProcessEmails();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            try
            {
                rootCategoryAlias = this.Page.RouteData.Values["parent-category-alias"].ToString();
                rootCategoryId = MixNP.BusinessLayer.Categories.GetCategoryId(rootCategoryAlias);

                categoryAlias = this.Page.RouteData.Values["category-alias"].ToString();
                categoryId = MixNP.BusinessLayer.Categories.GetCategoryId(categoryAlias);

                itemId = Pes.Utility.Conversion.TryCastInteger(this.Page.RouteData.Values["item-id"]);
                alias = this.Page.RouteData.Values["alias"].ToString();

                if (itemId == 0 || categoryId == 0 || rootCategoryId == 0)
                {
                    MixNP.BusinessLayer.Helpers.PageHelper.ContentNotFound(Context);
                    return;
                }

                if (!MixNP.BusinessLayer.Items.IsParentCategory(itemId, categoryId))
                {
                    MixNP.BusinessLayer.Helpers.PageHelper.ContentNotFound(Context);
                    return;
                }

                if (!MixNP.BusinessLayer.Categories.IsParentCategory(categoryId, rootCategoryId))
                {
                    MixNP.BusinessLayer.Helpers.PageHelper.ContentNotFound(Context);
                    return;
                }

                DisplayContent();
                DisplayCustomInfo();
                DisplayImages();
                DisplayAuthorProfile();
                SeoOptimization();
                IntegrateFacebook();
                IntegrateDisqus();

                MixNP.BusinessLayer.Items.Hit(itemId);

                if (Page.IsPostBack)
                {
                    #region Ajax methods
                    string method = Conversion.TryCastString(Request.Form["__EVENTTARGET"]);

                    if (method.Equals("CommentAdded"))
                    {
                        CommentAdded();
                        return;
                    }
                    #endregion
                }

            }
            catch (NullReferenceException)
            {
                MixNP.BusinessLayer.Helpers.PageHelper.ContentNotFound(Context);
            }
        }

        private void IntegrateFacebook()
        {
            string url = HttpContext.Current.Request.Url.AbsoluteUri;

            string html = @"
                <div class=""fb-like"" data-href=""{0}""
                    data-send=""true"" data-width=""450"" 
                    data-show-faces=""true"" data-font=""segoe ui"">
                </div>                
                <div class=""fb-comments"" data-href=""{0}""
                    data-width=""670"" data-num-posts=""10"" data-font=""segoe ui"">
                </div>";

            html = string.Format(html, url);

            html = @"
                <div id=""fb-root"">
                </div>
                <script type=""text/javascript"">        
                window.fbAsyncInit = function() {
                FB.init({
                    appId      : '126638197530307', // App ID
                    status     : true, // check login status
                    cookie     : true, // enable cookies to allow the server to access the session
                    xfbml      : true  // parse XFBML
                });


                    FB.Event.subscribe('comment.create', function(response) {
		                __doPostBack('CommentAdded', '');
                    });

                };

                (function (d, s, id) {
		                var js, fjs = d.getElementsByTagName(s)[0];
		                if (d.getElementById(id)) return;
		                js = d.createElement(s); js.id = id;
		                js.src = ""//connect.facebook.net/en_US/all.js"";
		                fjs.parentNode.insertBefore(js, fjs);

	                } 
	                (document, 'script', 'facebook-jssdk'));
                </script>" + html;

            FacebookLiteral.Text = html;
        }

        private void IntegrateDisqus()
        {
            string url = HttpContext.Current.Request.Url.AbsoluteUri;

            string html = @"
                            <div id=""disqus_thread"">
                            </div>
                            <script type=""text/javascript"">
	                            var trackComment = function () {
		                            __doPostBack('CommentAdded', '');
	                            }

	                            function disqus_config() {
		                            this.callbacks.onNewComment = [function () { trackComment(); } ];
	                            }

	                            var disqus_shortname = 'mixnp';
                                var disqus_identifier = '{0}';
                                var disqus_title = '{1}';
                                var disqus_url = '{2}';";

            if (HttpContext.Current.Request.IsLocal)
            {
                html += @"var disqus_developer = 1;";
            }

            html += @"
                                (function () {
		                            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
		                            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
		                            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
	                            })();
                            </script>
                            <noscript>
	                            Please enable JavaScript to view the
	                            <a href=""http://disqus.com/?ref_noscript"">comments powered by Disqus.</a>
                            </noscript>

                            <a href=""http://disqus.com"" class=""dsq-brlink"">comments powered by
	                            <span class=""logo-disqus"">
		                            Disqus</span>
                            </a>";

            html = html.Replace("{0}", itemId.ToString());
            html = html.Replace("{1}", itemTitle.Substring(0, (itemTitle.Length > 200) ? 200 : itemTitle.Length));
            html = html.Replace("{2}", url);
            DisqusLiteral.Text = html;
        }

        private void SeoOptimization()
        {
            this.Page.Title = itemTitle;
            this.Page.MetaKeywords = "kathmandu, nepal, MixNP, classifieds, buy, " + rootCategoryAlias + ", " + categoryAlias + ", " + alias;
            this.Page.MetaDescription = details.Trim().Substring(0, (details.Length < 128)? details.Trim().Length: 128);
        }

        private void DisplayContent()
        {
            itemTitle = MixNP.BusinessLayer.Items.GetTitle(itemId);
            string itemStatus = string.Empty;
            bool isNew = false;
            bool isPopular = false;

            using (DataTable item = MixNP.BusinessLayer.Items.GetItem(itemId))
            {
                if (item.Rows.Count == 1)
                {
                    DataRow row = item.Rows[0];
                    TitleLiteral.Text = Conversion.TryCastString(row["Title"]);
                    PriceLiteral.Text = "Buy this for Rs. " + Conversion.TryCastDecimal(row["Price"]).ToString("G29");
                    DetailsLiteral.Text = MixNP.BusinessLayer.Helpers.MarkdownTransformer.Transform(Conversion.TryCastString(row["Details"]));
                    details = Conversion.TryCastString(row["Details"]);

                    itemStatus = Conversion.TryCastString(row["ItemStatus"]);
                    isNew = Conversion.TryCastBoolean(row["IsNew"]);
                    isPopular = Conversion.TryCastBoolean(row["IsPopular"]);


                    if (itemStatus.Equals("Expired"))
                    {
                        RibbonLiteral.Text = "<div class=\"ribbon ribbon-orange\"><a href=\"#\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Expired&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a></div>";
                    }
                    else if (itemStatus.Equals("Sold"))
                    {
                        RibbonLiteral.Text = "<div class=\"ribbon ribbon-green\"><a href=\"#\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sold&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a></div>";
                    }
                    else if (itemStatus.Equals("Withdrawn"))
                    {
                        RibbonLiteral.Text = "<div class=\"ribbon ribbon-orange\"><a href=\"#\">&nbsp;&nbsp;&nbsp;&nbsp;Withdrawn&nbsp;&nbsp;&nbsp;&nbsp;</a></div>";
                    }
                    else if (itemStatus.Equals("Normal"))
                    {
                        if (isNew)
                        {
                            RibbonLiteral.Text = "<div class=\"ribbon\"><a href=\"#\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;New&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a></div>";
                        }

                        if (isPopular)
                        {
                            RibbonLiteral.Text = "<div class=\"ribbon\"><a href=\"#\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Popular&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a></div>";                        
                        }
                    }


                    CategoryHyperLink.Text = Conversion.TryCastString(row["CategoryName"]);

                    UserHyperLink.Text = Conversion.TryCastString(row["DisplayName"]);

                    AddedOnLabel.Text = Conversion.TryCastDate(row["AddedOn"]).ToShortDateString();
                    AddedOnLabel.ToolTip = "This ad was added on " + Conversion.TryCastDate(row["AddedOn"]).ToShortDateString() + ".";

                    LastEditedLabel.Text = Conversion.TryCastString(row["LastEditedOn"]);
                    LastEditedLabel.ToolTip = "This ad was last edited on " + Conversion.TryCastString(row["LastEditedOn"]) + ".";


                    int daysLeft = Conversion.TryCastInteger(row["DaysLeft"]);

                    if (daysLeft >= 0)
                    {
                        StatusLabel.Text = Conversion.TryCastString(daysLeft.ToString());

                        if (daysLeft.Equals(0))
                        {
                            StatusLabel.ToolTip = "This ad will expire tonight.";
                        }
                        else
                        {
                            StatusLabel.ToolTip = "This ad will expire in " + daysLeft.ToString() + " days.";                        
                        }
                    }
                    else
                    {
                        StatusLabel.Text = "<strong>Expired</strong>";
                        StatusLabel.ToolTip = "This ad expired " + (daysLeft * -1).ToString() + " days ago.";                    
                    }


                    TotalHitsLabel.Text = Conversion.TryCastString(row["TotalViews"]);
                    TotalHitsLabel.ToolTip = "This ad has a total " + Conversion.TryCastString(row["TotalViews"]) + " hits.";

                    int categoryId = Conversion.TryCastInteger(row["CategoryId"]);

                    CategoryHyperLink.NavigateUrl = MixNP.BusinessLayer.Categories.GetCategoryUrl(categoryId, this.Page);

                    userSalt = MixNP.BusinessLayer.Users.GetSaltFromEmailAddress(Conversion.TryCastString(row["EmailAddress"]));
                    UserHyperLink.NavigateUrl = ResolveUrl("~/user/" + userSalt + ".mix");
                }
            }
        }

        private void DisplayCustomInfo()
        {
            using (DataTable table = MixNP.BusinessLayer.Items.GetCustomFields(itemId))
            {
                using (DataTable otherTable = MixNP.BusinessLayer.Items.GetOtherFields(itemId))
                {
                    if (table.Rows.Count > 0 || otherTable.Rows.Count > 0)
                    {
                        StringBuilder builder = new StringBuilder();
                        string fieldType = string.Empty;
                        string label = string.Empty;
                        string value = string.Empty;

                        builder.Append("<table class=\"info-table\" id=\"details\">");


                        foreach (DataRow row in table.Rows)
                        {
                            fieldType = Conversion.TryCastString(row["FieldTypeName"]);
                            label = Conversion.TryCastString(row["FieldLabel"]);
                            value = Conversion.TryCastString(row["FieldValue"]);

                            builder.Append("<tr>");
                            builder.Append("<td style=\"width: 200px\">");
                            builder.Append(label);
                            builder.Append("</td>");
                            builder.Append("<td>");

                            if (fieldType.ToLower().Equals("url"))
                            {
                                builder.Append("<a href='" + value + "' rel='nofollow' title='" + value + "' target='_blank'>" + value + "</a>");
                            }
                            else
                            {
                                builder.Append(value);
                            }

                            builder.Append("</td>");
                            builder.Append("</tr>");
                        }

                        foreach (DataRow row in otherTable.Rows)
                        {
                            label = Conversion.TryCastString(row["FieldName"]);
                            value = Conversion.TryCastString(row["FieldValue"]);

                            builder.Append("<tr>");
                            builder.Append("<td style=\"width: 200px\">");
                            builder.Append(label);
                            builder.Append("</td>");
                            builder.Append("<td>");
                            builder.Append(value);

                            builder.Append("</td>");
                            builder.Append("</tr>");
                        }


                        builder.Append("</table>");

                        InformationPanel.Controls.Add(new Literal { ID = "InfoLiteral", Text = builder.ToString() });

                    }
                }
            }

        }

        private void DisplayImages()
        {
            using (DataTable table = MixNP.BusinessLayer.Items.GetImages(itemId))
            {
                if (table.Rows.Count > 0)
                {
                    StringBuilder html = new StringBuilder();
                    string filePath = string.Empty;

                    html.Append("<ul class=\"bpad8 thumb\">");

                    foreach (DataRow row in table.Rows)
                    {
                        filePath = ResolveUrl("~/Handlers/GetItemImage.ashx?Path=" + Conversion.TryCastString(row["FilePath"]));

                        html.Append("<li>");
                        html.Append("<a href='" + filePath + "'>");
                        html.Append("<img src='" + filePath + "&W=172&H=172' alt='" + itemTitle + "' />");
                        html.Append("</a>");
                        html.Append("</li>");
                    }

                    html.Append("</ul>");

                    ImageLiteral.Text = html.ToString();
                }
            }
        }

        private void DisplayAuthorProfile()
        {
            Author.Token = userSalt;
        }
    }
}